﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Utility.Helper
{
    public static class Json
    {
        /// <summary>
        /// Object 转 JToken(Newtonsoft.Json 基元素)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static JToken ToJToken(this object obj)
        {
            if (obj == null)
            {
                return null;
            }
            return JToken.FromObject(obj);
        }

        /// <summary>
        /// Object 转 JSON
        /// </summary>
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public static T GetValue<T>(this JToken jToken, string name)
        {
            if (jToken[name] == null)
            {
                return default(T);
            }
            else
            {
                return jToken[name].ToObject<T>();
            }
        }

        public static T NewToObject<T>(this JToken jToken)
        {
            if (jToken == null)
            {
                return default(T);
            }
            else
            {
                return jToken.ToObject<T>();
            }
        }
    }
}